package middleware

import (
	"local/common"
	"local/service_manager/web"

	"github.com/gin-contrib/sessions"
	"github.com/gin-gonic/gin"
)

// 检查密码状态的中间件
func CheckPasswordMiddleware(c *gin.Context) {
	// 如果admin.dat不存在，需要先创建密码
	if !web.IsAdminPasswordSet() && c.Request.URL.Path != "/create-password" &&
		c.Request.URL.Path != "/create-password.html" {
		common.Info("请设置管理员密码")
		c.Redirect(302, "/create-password.html")
		c.Abort()
		return
	}
	c.Next()
}

// 需要登录验证的中间件
func AuthRequired() gin.HandlerFunc {
	return func(c *gin.Context) {
		session := sessions.Default(c)
		if session.Get("authenticated") != true {
			// 检查是否是API请求
			if len(c.Request.URL.Path) >= 4 && c.Request.URL.Path[:4] == "/api" {
				c.JSON(401, gin.H{"error": "未登录"})
			} else {
				c.Redirect(302, "/login")
			}
			c.Abort()
			return
		}
		c.Next()
	}
}
